#include <stdio.h>
#include <assert.h>

void PrintArray(int* a, int n)
{
	assert(a);

	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);
	putchar('\n');
}

void Swap(int* p1, int* p2)
{
	assert(p1 && p2);

	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustDown(int* a, int parent, int n)
{
	assert(a && n);

	int child = 2 * parent + 1;

	while (child < n)
	{
		if (child + 1 < n && a[child + 1] > a[child])
			child++;

		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = 2 * parent + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapSort(int* a, int n)
{
	assert(a && n);

	if (1 == n)
	{
		return;
	}
	else
	{
		for (int parent = (n-1-1)/2; parent >= 0; parent--)
			AdjustDown(a, parent, n);

		int end = n - 1;
		while (end > 0)
		{
			Swap(&a[0], &a[end]);
			AdjustDown(a, 0, end);
			end--;
		}
	}
}

void HeapSortTest(void)
{
	int a[] = { 1, 3, 2, 5, 4, 6, 7 };

	PrintArray(a, sizeof(a) / sizeof(a[0]));
	HeapSort(a, sizeof(a) / sizeof(a[0]));
	PrintArray(a, sizeof(a) / sizeof(a[0]));
}



int main()
{
	HeapSortTest();

	return 0;
}